package com.sso.dao;

import com.sso.service.CustomService;
import com.sso.token.MultipleLoginAuthenticationToken;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Map;

public class MultipleLoginAuthenticationProvider implements AuthenticationProvider {

    private CustomService customService;

    private BCryptPasswordEncoder passwordEncoder;

    public MultipleLoginAuthenticationProvider() {

    }

    @Override
    @SuppressWarnings("unchecked")
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MultipleLoginAuthenticationToken authenticationToken = (MultipleLoginAuthenticationToken) authentication;

        Map<String, String> details = (Map<String, String>) authenticationToken.getDetails();
        // 获取自定义的loginType参数
        String username = details.get("username");
        String loginType = details.get("loginType");
        // 使用自定义的loginType在userDetailServceice中查询不同的数据库
        UserDetails user = this.customService.loadUserByUsernameAndLoginType(username,loginType);
        if (user == null) {
            throw new InternalAuthenticationServiceException(
                    "用户信息为空");
        }
        // if (!"APP".equals(loginType)) {
        // app登录不校验密码
        // 获取当前输入的密码
        String presentedPassword = authentication.getCredentials().toString();

        if (!passwordEncoder.matches(presentedPassword, user.getPassword())) {

            throw new BadCredentialsException("用户名或密码错误");
        }
        // }

        if (details.containsKey("password")) {
            details.put("password", null);
        }

        MultipleLoginAuthenticationToken authenticationResult = new MultipleLoginAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());


        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MultipleLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }


    public CustomService getCustomService() {
        return customService;
    }

    public void setCustomService(CustomService customService) {
        this.customService = customService;
    }


    public BCryptPasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
}
